def Denary2Binary(n):  #this is used with all_permutations, explanation below
    '''convert denary (base 10) integer n to binary string bStr'''
    bStr = ''
    if n < 0:  raise ValueError, "must be a positive"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1
    return bStr

def all_permutations(list): 
	'''This is used to cycle through every binary representation, starting with a string of 1s as long as the variable list
	Doing binary decrements on this number, and taking the variables on the list that correspond to the 1s, ensures that
	there is a sublist with each combination of variables.
	'''
	all_lists = []
	iterations = 2**(len(list)) - 1 #creates the big list of 1s
	for i in range(iterations+1):
		binary = Denary2Binary(int(i))
		binary = binary[::-1] #inverts the list, since python starts counting from the highest digit, and drops leading zeros
		sublist = []
		for digit_index in range(len(binary)):
			if binary[digit_index] == '1': sublist.append(list[digit_index])
		all_lists.append(sublist)
	return all_lists[1:] #the first list is always empty
	
def restrict_tag(request):
	if request.POST: #if there is a request
		restrictions = list(request.session['restrictions'])
		restriction_set = list(request.session['restriction_set'])
		new_restriction = Restriction.objects.filter(name = request.POST.get('restrict'))
		restrictions.extend(new_restriction)
		restriction_set.remove(new_restriction[0])
		
		index_cards = request.session['index_cards']
		
			
		new_index_cards = []
		for card in index_cards:
			for restriction in card[0].restrictions.all():
				if not restriction in restrictions:
					new_index_cards.append(card)


		request.session['restrictions'] = restrictions
		request.session['restriction_set'] = restriction_set
		request.session['index_cards'] = new_index_cards
		
		return render_to_response('cards/cards2.html', 
						  {'index_cards': new_index_cards,
						   'restriction_set': restriction_set,
						   'tagquery':request.session['tagquery_request'],
						   'unrecognized_variables': request.session['unrecognized_variables'],
						   'recognized_variables': request.session['recognized_variables'],		
						   'restrictions': restrictions,
						   })
